package validator

import (
	"errors"
	"log"
	"reflect"

	"github.com/dlclark/regexp2"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

func Validate(dataStruct interface{}) error {

	//验证
	zh_ch := zh.New()
	validate := validator.New()
	//自定义校验
	validate.RegisterValidation("RegexPhone", PhoneValidation)
	//注册一个函数，获取struct tag里自定义的label作为字段名
	validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
		name := fld.Tag.Get("label")
		return name
	})

	uni := ut.New(zh_ch)
	trans, _ := uni.GetTranslator("zh")
	//验证器注册翻译器
	zh_translations.RegisterDefaultTranslations(validate, trans)
	err := validate.Struct(dataStruct)
	if err != nil {
		for _, err := range err.(validator.ValidationErrors) {
			if err.Tag() == "RegexPhone" {
				return errors.New("手机号码不规范")
			}
			return errors.New(err.Translate(trans))
		}
	}
	return nil
}

// phone 校验
func PhoneValidation(f1 validator.FieldLevel) bool {
	verificationRole := `^(13[0-9]|14[57]|15[0-9]|18[0-9]|16[0-9])\d{8}$`
	field := f1.Field()
	switch field.Kind() {
	case reflect.String:
		re, err := regexp2.Compile(verificationRole, 0)
		if err != nil {
			log.Println(err.Error())
			return false
		}
		response, _ := re.MatchString(field.String())
		return response
	default:
		return false
	}
}
